<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="房屋名称" prop="houseName">
        <el-input
            v-model="queryParams.houseName"
            placeholder="请输入房屋名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房屋状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择房屋状态" clearable style="width: 100px;">
          <el-option
              v-for="dict in house_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="空调:" prop="hasAirConditioner">
        <el-select v-model="queryParams.hasAirConditioner" placeholder="请选择空调:" clearable style="width: 100px;">
          <el-option
              v-for="dict in has_aircondition"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="朝向" prop="orientation">
        <el-select v-model="queryParams.orientation" placeholder="请选择朝向" clearable style="width: 100px;">
          <el-option
              v-for="dict in house_toward"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电梯" prop="hasElevator">
        <el-select v-model="queryParams.hasElevator" placeholder="请选择电梯" clearable style="width: 100px;">
          <el-option
              v-for="dict in has_aircondition"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['house:house:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['house:house:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['house:house:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['house:house:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="房屋名称" align="center" prop="houseName"/>
      <el-table-column label="房屋状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="house_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="租金 (元/月)" align="center" prop="rent"/>
      <el-table-column label="房产证编号" align="center" prop="propertyCertificateNo"/>
      <el-table-column label="卧室" align="center" prop="bedroomCount"/>
      <el-table-column label="卫生间" align="center" prop="bathroomCount"/>
      <el-table-column label="厨房" align="center" prop="kitchenCount"/>
      <el-table-column label="客厅" align="center" prop="livingroomCount"/>
      <el-table-column label="房屋面积 (m²)" align="center" prop="area"/>
      <el-table-column label="空调:" align="center" prop="hasAirConditioner">
        <template #default="scope">
          <dict-tag :options="has_aircondition" :value="scope.row.hasAirConditioner"/>
        </template>
      </el-table-column>
      <el-table-column label="建成年份" align="center" prop="buildYear"/>
      <el-table-column label="朝向" align="center" prop="orientation">
        <template #default="scope">
          <dict-tag :options="house_toward" :value="scope.row.orientation"/>
        </template>
      </el-table-column>
      <el-table-column label="楼层" align="center" prop="floor"/>
      <el-table-column label="电梯" align="center" prop="hasElevator">
        <template #default="scope">
          <dict-tag :options="has_aircondition" :value="scope.row.hasElevator"/>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contactName"/>
      <el-table-column label="联系电话" align="center" prop="contactPhone"/>
      <!--<el-table-column label="描述" align="center" prop="description" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['house:house:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['house:house:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Edit" @click="uploadImage(scope.row.id)"
                     v-hasPermi="['house:house:addImage']">添加图片
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <el-dialog title="上传图片" v-model="uploadImageVisible" width="50vw" append-to-body>
      <ImageUpload v-model="fileList"/>
      <el-button @click="addImage">确定</el-button>
    </el-dialog>

    <!-- 添加或修改房源对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="houseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房屋名称" prop="houseName">
          <el-input v-model="form.houseName" placeholder="请输入房屋名称"/>
        </el-form-item>
        <el-form-item label="房屋状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择房屋状态">
            <el-option
                v-for="dict in house_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租金 (元/月)" prop="rent">
          <el-input v-model="form.rent" placeholder="请输入租金 (元/月)"/>
        </el-form-item>
        <el-form-item label="房产证编号" prop="propertyCertificateNo">
          <el-input v-model="form.propertyCertificateNo" placeholder="请输入房产证编号"/>
        </el-form-item>
        <el-form-item label="卧室数量" prop="bedroomCount">
          <el-input v-model="form.bedroomCount" placeholder="请输入卧室数量"/>
        </el-form-item>
        <el-form-item label="卫生间数量" prop="bathroomCount">
          <el-input v-model="form.bathroomCount" placeholder="请输入卫生间数量"/>
        </el-form-item>
        <el-form-item label="厨房数量" prop="kitchenCount">
          <el-input v-model="form.kitchenCount" placeholder="请输入厨房数量"/>
        </el-form-item>
        <el-form-item label="客厅数量" prop="livingroomCount">
          <el-input v-model="form.livingroomCount" placeholder="请输入客厅数量"/>
        </el-form-item>
        <el-form-item label="房屋面积 (m²)" prop="area">
          <el-input v-model="form.area" placeholder="请输入房屋面积 (m²)"/>
        </el-form-item>
        <el-form-item label="空调:" prop="hasAirConditioner">
          <el-select v-model="form.hasAirConditioner" placeholder="请选择空调:">
            <el-option
                v-for="dict in has_aircondition"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建成年份" prop="buildYear">
          <el-input v-model="form.buildYear" placeholder="请输入建成年份"/>
        </el-form-item>
        <el-form-item label="朝向" prop="orientation">
          <el-select v-model="form.orientation" placeholder="请选择朝向">
            <el-option
                v-for="dict in house_toward"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层"/>
        </el-form-item>
        <el-form-item label="电梯" prop="hasElevator">
          <el-select v-model="form.hasElevator" placeholder="请选择电梯">
            <el-option
                v-for="dict in has_aircondition"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="6" autosize></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="House">
import {listHouse, getHouse, delHouse, addHouse, updateHouse, getImagesApi, uploadImageApi} from "@/api/house/house.js";
import ImageUpload from '@/components/ImageUpload'


const uploadImageVisible = ref(false);

const fileList = ref('')
const id = ref(0)

const addImage = () => {
  console.log(typeof fileList.value, '1')
  const images = []
  fileList.value.split(",").forEach(item => {
    images.push({imageUrl: item})
  })
  uploadImageApi(id.value, images).then(res => {
    proxy.$message.success('上传成功')
    uploadImageVisible.value = false
    fileList.value = ''
  })
}

const uploadImage = (i) => {
  id.value = i
  uploadImageVisible.value = true
  getImagesApi(id.value).then(res => {
    fileList.value = res.data
    console.log(res.data, '111')
  })
}

const {proxy} = getCurrentInstance();
const {
  house_status,
  has_aircondition,
  house_toward
} = proxy.useDict('house_status', 'has_aircondition', 'house_toward');

const houseList = ref([]);
const houseImageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedHouseImage = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    houseName: null,
    status: null,
    hasAirConditioner: null,
    orientation: null,
    hasElevator: null,
  },
  rules: {
    houseName: [
      {required: true, message: "房屋名称不能为空", trigger: "blur"}
    ],
    rent: [
      {required: true, message: "租金 (元/月)不能为空", trigger: "blur"}
    ],
    propertyCertificateNo: [
      {required: true, message: "房产证编号不能为空", trigger: "blur"}
    ],
    bedroomCount: [
      {required: true, message: "卧室数量不能为空", trigger: "blur"}
    ],
    bathroomCount: [
      {required: true, message: "卫生间数量不能为空", trigger: "blur"}
    ],
    kitchenCount: [
      {required: true, message: "厨房数量不能为空", trigger: "blur"}
    ],
    livingroomCount: [
      {required: true, message: "客厅数量不能为空", trigger: "blur"}
    ],
    area: [
      {required: true, message: "房屋面积 (m²)不能为空", trigger: "blur"}
    ],
    buildYear: [
      {required: true, message: "建成年份不能为空", trigger: "blur"}
    ],
    orientation: [
      {required: true, message: "朝向不能为空", trigger: "change"}
    ],
    floor: [
      {required: true, message: "楼层不能为空", trigger: "blur"}
    ],
    contactName: [
      {required: true, message: "联系人不能为空", trigger: "blur"}
    ],
    contactPhone: [
      {required: true, message: "联系电话不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询房源列表 */
function getList() {
  loading.value = true;
  listHouse(queryParams.value).then(response => {
    houseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    houseName: null,
    status: null,
    rent: null,
    propertyCertificateNo: null,
    bedroomCount: null,
    bathroomCount: null,
    kitchenCount: null,
    livingroomCount: null,
    area: null,
    hasAirConditioner: null,
    buildYear: null,
    orientation: null,
    floor: null,
    hasElevator: null,
    contactName: null,
    contactPhone: null,
    description: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    auditStatus: null
  };
  houseImageList.value = [];
  proxy.resetForm("houseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加房源";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getHouse(_id).then(response => {
    form.value = response.data;
    houseImageList.value = response.data.houseImageList;
    open.value = true;
    title.value = "修改房源";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["houseRef"].validate(valid => {
    if (valid) {
      form.value.houseImageList = houseImageList.value;
      if (form.value.id != null) {
        updateHouse(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHouse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除房源编号为"' + _ids + '"的数据项？').then(function () {
    return delHouse(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 房屋图片序号 */
function rowHouseImageIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 房屋图片添加按钮操作 */
function handleAddHouseImage() {
  let obj = {};
  obj.imageUrl = "";
  houseImageList.value.push(obj);
}

/** 房屋图片删除按钮操作 */
function handleDeleteHouseImage() {
  if (checkedHouseImage.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的房屋图片数据");
  } else {
    const houseImages = houseImageList.value;
    const checkedHouseImages = checkedHouseImage.value;
    houseImageList.value = houseImages.filter(function (item) {
      return checkedHouseImages.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleHouseImageSelectionChange(selection) {
  checkedHouseImage.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('house/house/export', {
    ...queryParams.value
  }, `house_${new Date().getTime()}.xlsx`)
}

getList();
</script>
